package com.secneo.appshare.adapter;

import java.util.List;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.secneo.appshare.R;
import com.secneo.appshare.api.RemoteApi.AppRecom;

public class RecomAdapter extends BaseAdapter {
	private List<AppRecom> mList;
	private Context mContext;
	private boolean mStoped;
	private int mCount;
	
	public RecomAdapter(Context ctx, List<AppRecom> list) {
		this.mContext = ctx;
		this.mList = list;
		this.mStoped = false;
		mCount = mList.size();
	}
	
	public void appandAdapter(List<AppRecom> list) 
	{
		for(int i=0; i<list.size(); i++)
		{
			mList.add(list.get(i));
			mCount++;
		}
	}
	
	public void freeDrawable()
	{
		mStoped = true;
		Log.d("MyTag", "Apps bitmaps free !!! ");
		for(int i=0; i<mList.size(); i++)
		{
			BitmapDrawable a = (BitmapDrawable) mList.get(i).app_icon_drawable;
			if(a!=null && !a.getBitmap().isRecycled())
				a.getBitmap().recycle();
			mList.get(i).app_icon_drawable = null;
		}
		System.gc();
	}
	
	@Override
	public int getCount() {
		return mCount;
	}

	@Override
	public Object getItem(int position) {
		return mList.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) 
	{
		if(mStoped)
			return convertView;
		AppItem appItem;
		AppRecom app = mList.get(position);
		if (convertView == null) 
		{
			View v = LayoutInflater.from(mContext).inflate(R.layout.appshare_app_item, null);
			
			appItem = new AppItem();
			appItem.mAppIcon = (ImageView)v.findViewById(R.id.ivAppIcon);
			appItem.mAppName = (TextView)v.findViewById(R.id.tvAppName);
			appItem.mAppName.setTextColor(android.graphics.Color.BLACK);
			v.setTag(appItem);
			convertView = v;
		} else 
		{
			appItem = (AppItem)convertView.getTag();
		}
		if (app.app_icon_drawable == null)
			appItem.mAppIcon.setImageResource(R.drawable.some_app);
		else
			appItem.mAppIcon.setImageDrawable(app.app_icon_drawable);
		appItem.mAppName.setText(app.app_name);
		return convertView;
	}

	class AppItem {
		ImageView mAppIcon;
		TextView mAppName;
	}
}
